package com.y.fund.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

public class JsonUtil {
	private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);

	/**使用mapperIncludeNON_NULL转换的全局忽略值为null的属性 */
	protected static final ObjectMapper mapperIncludeNON_NULL = new ObjectMapper(); 
	protected static final ObjectMapper mapper = new ObjectMapper(); 
	
	static {
		mapperIncludeNON_NULL.registerModule(new ParameterNamesModule())
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		 // 全局忽略值为null的字段
		mapperIncludeNON_NULL.setSerializationInclusion(JsonInclude.Include.NON_NULL);

		mapper.registerModule(new ParameterNamesModule())
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	/** 将对象转换为JSON字符串,  忽略空格  */
    public static String serializer(Object obj) {
		try{
			return mapperIncludeNON_NULL.writeValueAsString(obj);
		}catch(Exception e){
			e.printStackTrace();
			e = null;
		}
		return "{}";
    }

	/** 将对象转换为JSON字符串
	 * @param includeNullAttr 是否忽略值为null的属性；true则包含属性值为null的属性；否则忽略【和serializer(Object obj)效果相同】； */
    public static String serializer(Object obj, boolean includeNullAttr) {
    	if(includeNullAttr) {
    		try{
    			return mapper.writeValueAsString(obj);
    		}catch(Exception e){
    			e.printStackTrace();
    			e = null;
    		}
    		return "{}";
    	}else {
    		return serializer(obj);
    	}
    } 
    
	/** 将JSON字符串转换为对象*/
    public static <T> T deSerializer(String jsonStr, Class<T> clazz) {
		if(isBlank(jsonStr)){
			return null;
		}
		try{
			return mapper.readValue(jsonStr, clazz);
		}catch(Exception e){
			e.printStackTrace();
			e = null;
		}
		return null;
    }

    /** 解析 */
    public static <T> List<T> deSerializerList(String jsonStr, Class<T> clazz) {
		if(null==clazz || isBlank(jsonStr)){
			return null;
		}
		try{
	        JavaType javaType = getCollectionType(List.class, clazz); 
	        List<T> lst = mapper.readValue(jsonStr, javaType); 
			return lst;
		}catch(Exception e){
			if(null!=jsonStr && jsonStr.indexOf("{") < 0) {
				log.error("deSerializerList(clazz)出现错误，也许是数据被发送端加密了此处尚未解密.datastr:{}, clazz：{}", jsonStr, clazz);
			}
			e.printStackTrace();
			e = null;
		}
		return null;
    }
    
	 /** 
	  *  获取泛型的Collection Type  
     * @param collectionClass 泛型的Collection   
     * @param elementClasses 元素类   
     * @return JavaType Java类型   
     * @since 1.0   
     */   
 	 public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
 	     return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
 	 }


	/** Parsing JSON files into strings  */
	public static String parseFile(String jsonFilePath){
		File f = new File(jsonFilePath);
		if(null==f || !f.exists()){
			return null;
		}
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream(f));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		StringBuffer sb = new StringBuffer();
		char [] chs = new char[1024];
		int len = 1;
		try {
			while((len=isr.read(chs))!=-1){
				sb.append(chs, 0, len);
			}
			isr.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}

	protected static boolean isBlank(final String str){
		return (null==str || str.trim().length()<1);
	}

	public static JSONObject toJSONObject(String str) {
		if(null==str || str.trim().length()<1) {
			return null;
		}
		try {
			return JSONObject.parseObject(str);
		} catch (Exception e) {
			System.err.println("将字符串转换为JSONObject时失败，可能传入的字符串不是规范的JSON字符串内容");
			e.printStackTrace();
			return null;
		}
	}

	public static JSONArray toJSONArray(String str, Boolean... newEmptyIfNull) {
		if(null==str || str.trim().length()<1) {
			if(newEmptyIfNull.length>0 && newEmptyIfNull[0]) {
				return JSONArray.of();
			}else {
				return null;
			}
		}
		try {
			return JSONArray.parseArray(str);
		} catch (Exception e) {
			System.err.println("将字符串转换为JSONArray时失败，可能传入的字符串不是规范的JSONArray字符串内容");
			e.printStackTrace();
			if(newEmptyIfNull.length>0 && newEmptyIfNull[0]) {
				return JSONArray.of();
			}else {
				return null;
			}
		}
	}
	
}
